import React, { useState, useEffect } from 'react'
import { Card, Row, Col, Spin, Alert, Button, Space } from 'antd'
import { ReloadOutlined, DollarOutlined, BankOutlined } from '@ant-design/icons'
import { apiService, LatestRatesResponse } from '../services/api'
import dayjs from 'dayjs'

const LatestCards: React.FC = () => {
  const [data, setData] = useState<LatestRatesResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)
      const result = await apiService.getLatestRates()
      setData(result)
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
    
    // 每30秒自动刷新
    const interval = setInterval(fetchData, 30000)
    return () => clearInterval(interval)
  }, [])

  const handleRefresh = () => {
    fetchData()
  }

  if (loading && !data) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>加载中...</div>
      </div>
    )
  }

  if (error) {
    return (
      <Alert
        message="数据加载失败"
        description={error}
        type="error"
        action={
          <Button size="small" onClick={handleRefresh}>
            重试
          </Button>
        }
        showIcon
      />
    )
  }

  if (!data) {
    return <Alert message="暂无数据" type="warning" showIcon />
  }

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2 style={{ margin: 0 }}>最新汇率</h2>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      </div>
      
      <Row gutter={16}>
        <Col xs={24} sm={12}>
          <Card 
            className="rate-card"
            title={
              <Space>
                <BankOutlined style={{ color: '#1890ff' }} />
                JPY → CNY
              </Space>
            }
          >
            <div className="rate-value">
              {data.jpy_cny.rate.toFixed(6)}
            </div>
            <div className="rate-amount">
              1000 JPY = {data.jpy_cny.amount_1000.toFixed(2)} CNY
            </div>
            <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
              更新时间: {dayjs(data.jpy_cny.ts_utc).format('MM-DD HH:mm:ss')}
            </div>
          </Card>
        </Col>
        
        <Col xs={24} sm={12}>
          <Card 
            className="rate-card"
            title={
              <Space>
                <DollarOutlined style={{ color: '#52c41a' }} />
                JPY → USD
              </Space>
            }
          >
            <div className="rate-value">
              {data.jpy_usd.rate.toFixed(6)}
            </div>
            <div className="rate-amount">
              1000 JPY = {data.jpy_usd.amount_1000.toFixed(2)} USD
            </div>
            <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
              更新时间: {dayjs(data.jpy_usd.ts_utc).format('MM-DD HH:mm:ss')}
            </div>
          </Card>
        </Col>
      </Row>
      
      <div style={{ marginTop: 16, textAlign: 'center', color: '#999', fontSize: 12 }}>
        最后更新: {dayjs(data.last_updated).format('YYYY-MM-DD HH:mm:ss')}
      </div>
    </div>
  )
}

export default LatestCards
